<?php

/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace common\rest\controllers;

use Yii;
use yii\rest\Controller as BaseController;
use yii\filters\ContentNegotiator;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\filters\RateLimiter;
use yii\filters\Cors;

/**
 * Controller is the base class for RESTful API controller classes.
 *
 * Controller implements the following steps in a RESTful API request handling cycle:
 *
 * 1. Resolving response format (see [[ContentNegotiator]]);
 * 2. Validating request method (see [[verbs()]]).
 * 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]);
 * 4. Rate limiting (see [[RateLimiter]]);
 * 5. Formatting response data (see [[serializeData()]]).
 *
 * For more details and usage information on Controller, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Controller extends BaseController
{

    public $serializer = [
        'class' => 'common\rest\components\Serializer',
        'collectionEnvelope' => 'data',
    ];

    public function beforeAction($action)
    {
        Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function ($event) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            // $response = $event->sender;
            // if (!$response->isSuccessful) {
            //     $response->data = \common\rest\statics\ResponseDatum::getErrorDatum([
            //         'code' => !empty($response->data['code']) ? $response->data['code'] : OperationResult::ERROR_INTERNAL,
            //         'msg' => !empty($response->data['message']) ? $response->data['message'] : "",
            //     ]);
            // }
        });
        return parent::beforeAction($action);
    }

    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
            ],
            [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['http://api-v2.local.dev', 'http://localhost:5051', 'http://localhost:5052'],
                    'Access-Control-Allow-Origin' => ['*'],
                    'Access-Control-Request-Method' => ['*'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 3600,
                    'Access-Control-Expose-Header' => ['X-Pagination-Current-Page'],
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
            'rateLimiter' => [
                'class' => RateLimiter::className(),
            ],
        ];
    }

    /**
     * inherit
     * @param type $id
     * @return Model
     */
    protected function findModel($id)
    {
        return null;
    }

    /**
     *
     * @param type $id
     * @param type $allowReturnNew
     * @return Model
     * @throws NotFoundHttpException
     */
    public function retrieveModel($id = null, $allowReturnNew = true)
    {
        if (!is_null($id) && $id != '') {
            $model = $this->findModel($id);
        } elseif (!$allowReturnNew) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } else {
            $model = new $this->modelClass;
            $model->loadDefaultValues();
        }
        return $model;
    }

}
